#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>

const int gid = -1;
const int gsize = 4096;
const std::string pathname = ".";
const int projid = 0x66;
const int gmode = 0666;
#define CREATR "creatr"
#define USER "user"

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

class Shm
{
private:
    // 创建新的共享内存
    void CreateHelp(int flg)
    {
        printf("key: 0x%x\n", _key);
        _shmid = shmget(_key, _size, flg);
        if (_shmid < 0)
        {
            ERR_EXIT("shmgt");
        }
        printf("_shmid: %d\n", _shmid);
    }

    void Create()
    {
        CreateHelp(IPC_CREAT | IPC_EXCL | gmode);
    }

    void Get()
    {
        CreateHelp(IPC_CREAT);
    }

    void Attach()
    {
        _start_men = shmat(_shmid, nullptr, 0);
        //-1 出错
        if ((long long)_start_men < 0)
        {
            ERR_EXIT("_atart_men");
        }
        printf("attach successful");
    }

    //进行共享内存分离 进程和共享内存进行分离
    void Detach()
    {
        int n = shmdt(_start_men);
        if(n == 0)
        {
            printf("detach successful!\n");
        }
    }

    //共享内存的属性 调用shmctl
    void Attr()
    {
        struct shmid_ds ds;
        int n = shmctl(_shmid,IPC_STAT,&ds);
        printf("shm_size:%ld\n",ds.shm_segsz);
        printf("key: 0x%x\n",ds.shm_perm.__key);
    }
    void Destory()
    {
        if (_shmid == gid)
            return;
       
        if (_usertype == CREATR)
        {
            int n = shmctl(_shmid, IPC_RMID, nullptr);
            if (n > 0)
            {
                printf("shmctl delete shm: %d success!\n", _shmid);
            }
            else
            {
                ERR_EXIT("shmctl");
            }
        }
    }

public:
    Shm(const std::string &pathname, int projid, const std::string usertype)
        : _shmid(gid), _size(gsize), _start_men(nullptr), _usertype(usertype)
    {
        _key = ftok(pathname.c_str(), projid);
        if (_key < 0)
        {
            ERR_EXIT("ftok");
        }
        if (_usertype == CREATR)
        {
            Create();
        }
        else if (_usertype == USER)
        {
            Get();
        }
        else
        {
        }
        Attach();
    }

    // 返回虚拟地址
    void *VirtualAddr()
    {
        printf("虚拟起始地址: %p\n", _start_men);
        return _start_men;
    }

    int Size()
    {
        return _size;
    }
    ~Shm()
    {
        Detach();
        if (_usertype == CREATR)
            Destory();
    }

private:
    int _shmid;
    key_t _key;
    int _size;
    void *_start_men;
    std::string _usertype;
};